<template>
  <paper-template :item="item" :pageId="pageId" :popId="popId" :isPropagation="false">
    <template v-slot:common>
      <canvas v-if="!isSVG" :id="getCanvasId" ref="canvasCon" class="wb-paper" :style="styles" @click.stop resize></canvas>
    </template>
  </paper-template>
</template>
<script>
import PaperTemplate from '@/components/games/paper/paper-template.vue'
import { utils } from '@/components/utils/utils'
import { commonUtils } from '@/components/utils/common-utils'
import { COLORS } from '@/common/const-colors'
import { isJSON } from '@/plugins/utils'
import { PAPER_TYPE_MAP } from '@/common/const-wb'
import { EventBus } from '@/store/index'
import { ref } from 'vue'

export default {
  name: "WbPaper",
  mixins: [utils, commonUtils],
  props: ['item'],
  setup () {
    return {
      isSVG: ref(false),
      tool: null,
      path: null,
      canvasCon: null,
      paperObj: {
        tool: { minDistance: 10 },
        simplifySegment: 10,
        strokeCap: "round",//分段和拐角处使用的形状 'miter', 'round', 'bevel'
        strokeJoin: "round",//'miter', 'round', 'bevel'
        fullySelected: false,//指定是否选择路径及其所有线段
        isRandomColor: true,
        strokeWidth: 4,
        strokeColor: "black",
        fillColor: "black",
        colorLength: 10,
        colors: ["#F0F8FF","#A52A2A","#FF1493","#FFD700","#ADFF2F","#800000","#FF4500","#CD853F","#FF0000","#FF6347","#9ACD32"],
        colorWidth: 50,
        colorHeight: 20,
        colorCap: 4,
        colorOffset: 20,
        isClosed: true,
      },
      isDragUp: true,
      // isVisible: ref(true),
    }
  },
  created() {
    if(!this.isH5Edit) {
      if(this.commonAttr.params && isJSON(this.commonAttr.params)) {
        _.merge(this.paperObj, JSON.parse(this.commonAttr.params))
      }
      if(!window.paper) {
        this.dynamicsLoadScript(this.env.baseUrl + 'js/paper/paper-full.min.js', "paper", this.initPaper)
      } else {
        this.initPaper(window.paper);
      }

      EventBus.$on("paperData", this.onChangePaperObj);
      EventBus.$on("exportSVG", this.onExportSVG);
      EventBus.$on("clearPaper", this.onClearPaper);
    }
  },
  components: {
    PaperTemplate
  },
  computed: {
    lists() {
      return this.item.lists
    },
    styles() {
      return {
        transform: 'rotate(' + this.item.commonAttr.rotate + 'deg)',
        opacity: this.item.commonAttr.opacity,
        width: this.item.conStyles.width,
        height: this.item.conStyles.height,
        backgroundColor: this.item.styles.backgroundColor,
      }
    },
    getCanvasId() {
      return 'canvas-' + this.item.id
    }
   },
  mounted(){
    if(!this.isH5Edit) {
      this.initPaper(window.paper);
    }
  },
  methods: {
    onClearPaper(){
      this.paper.project.activeLayer.removeChildren(); 
      // this.paper.view.draw(); 
    },
    onChangePaperObj(paperObj) {
      _.merge(this.paperObj, paperObj);
    },
    initPaper(paper) {
      if(!paper) {
        return;
      }
      paper.setup(this.$refs.canvasCon);
      this.paper = paper;
      this.viewWidth = this.paper.view.size.width;

      if(this.commonAttr.itemType == PAPER_TYPE_MAP.freedomDraw) {
        let tool = this.tool = new paper.Tool();
        tool.minDistance = this.paperObj.tool.minDistance;
        tool.onMouseDown = this.onMouseDown;
        tool.onMouseDrag = this.onMouseDrag;
        tool.onMouseUp = this.onMouseUp;
        if(!this.paperObj.isNotColorTool){ // 是否显示颜色空板
          this.initColors();
        }
      } else if(this.commonAttr.itemType == PAPER_TYPE_MAP.drawColors) {
      }

      
    },
    initColors() {
      const colorLength = COLORS.length;
      // let originals = new this.paper.Group({ insert: false }); // Don't insert in DOM.
      let colorLists = _.drop(_.shuffle(COLORS), colorLength - this.paperObj.colorLength);
      let viewWidth = this.viewWidth;
      let colorRect;
      _.forEach(colorLists, (colorItem, index) => {
        colorRect = new this.paper.Path.Rectangle({
          position: new paper.Size(viewWidth-this.paperObj.colorWidth/2, index*(this.paperObj.colorHeight + this.paperObj.colorCap) + this.paperObj.colorOffset),
          rectangle: { size: [this.paperObj.colorWidth, this.paperObj.colorHeight] },
          fillColor: colorItem.value
        });
        colorRect.data.color = colorItem.value;
        colorRect.onClick = this.onClickColor;
      })
    },
    onClickColor(event) {
      this.isDragUp = false;
      if(this.path) {
        if(this.path.data.isClosed) {
          this.path.fillColor = event.currentTarget.data.color;
        } else {
          this.path.strokeColor = event.currentTarget.data.color;
        }
      }
    },
    onMouseDown(event) {
      // || event.point.y < 100
      if(event.point.x > this.viewWidth - this.paperObj.colorWidth) {
        return
      }
      if (this.path) {
        this.path.selected = false;
      }
      if(event.item) {
        this.path = event.item
        this.path.selected = true;
        return
      }
      let paper = this.paper;
      const colorLength = COLORS.length - 1;
      let strokeColor = this.paperObj.strokeColor;
      if(this.paperObj.isRandomColor) {
        strokeColor = COLORS[_.random(0, colorLength)].value;
      }
      this.path = new paper.Path({
        segments: [event.point],
        strokeColor: strokeColor,
        strokeWidth: this.paperObj.strokeWidth,
        strokeCap: this.paperObj.strokeCap,
        strokeJoin: this.paperObj.strokeJoin,
        // dashArray: [10, 12],
        // fullySelected: true
      });
      this.isDragUp = true;
    },
    onMouseDrag(event) {
      if(!this.path || !this.isDragUp) {
        return
      }
      this.path.add(event.point);
    },
    onMouseUp() {
      if(!this.path || !this.isDragUp) {
        return
      }
      const colorLength = COLORS.length - 1;
      let fillColor = this.paperObj.fillColor;
      if(this.paperObj.isRandomColor) {
        fillColor = COLORS[_.random(0, colorLength)].value;
      }
      if(this.paperObj.isClosed) {
        this.path.fillColor = fillColor;
      }
      this.path.closed = this.paperObj.isClosed;
      this.path.data.isClosed = this.paperObj.isClosed;
      // let segmentCount = path.segments.length;
      this.path.simplify(this.paperObj.segmentCount);
      // this.path.smooth();
      this.path.fullySelected = true;
    },
    loadScript(url) {
      let script = document.createElement("script");
      script.type = "text/paperscript";
      script.src = url;
      script.setAttribute("canvas", this.getCanvasId);
      document.body.appendChild(script);
    },
    onExportSVG() {
      this.canvasCon = document.getElementsByClassName("paper-con")[0];
      let svg = this.svg = this.paper.project.exportSVG();
      svg.style.position = "absolute";
      svg.style.left = "0";
      svg.style.top = "0";
      svg.style.width = "100%";
      svg.style.height = "100%";
      this.canvasCon.appendChild(svg);
      this.isSVG = true;
    }
  },
  beforeUnmount() {
    if(this.paper) {
      this.paper.project.clear();
      this.paper.project.remove();
    }
    EventBus.$off("paperData", this.onChangePaperObj);
    EventBus.$off("exportSVG", this.onExportSVG);
    if(this.svg) {
      this.canvasCon.removeChild(this.svg);
    }
    this.canvasCon = null;
    this.tool = null;
    this.path = null;
    this.svg = null;
    this.isSVG = false;
    this.paperObj = null;
  },
};
</script>
<style lang="scss">
.wb-paper {
  width: inherit;
  height: inherit;
  background-color: transparent;

  canvas{
    width: inherit;
    height: inherit;
    background-color: transparent;
  }
  canvas[resize] {
    width: 100%;
    height: 100%;
  } 

  img{
    object-fit: contain;
    width: 100%;
  }
}
</style>


